package cn.com.lms.business.examRewrite.web;

import cn.com.lms.business.core.constant.ErrorEnum;
import cn.com.lms.business.core.util.SystemUserUtil;
import cn.com.lms.business.exam.enums.SubjectTypeEnum;
import cn.com.lms.business.examRewrite.enums.PaperTypeEnum;
import cn.com.lms.business.examRewrite.persistence.entity.PaperExtraReWrite;
import cn.com.lms.business.examRewrite.persistence.entity.PaperReWrite;
import cn.com.lms.business.examRewrite.service.PaperExtraReWriteService;
import cn.com.lms.business.examRewrite.service.PaperQuestionReWriteService;
import cn.com.lms.business.examRewrite.service.PaperReWriteService;
import cn.com.lms.business.examRewrite.service.PaperSubjectReWriteService;
import cn.com.lms.business.examRewrite.vo.PaperDetailRwWriteVO;
import cn.com.lms.business.examRewrite.vo.PaperListReWriteVO;
import cn.com.lms.business.user.persistence.entity.SysUserVo;
import com.bnzj.core.exception.BusinessException;
import com.bnzj.core.persistence.query.CompareExpression;
import com.bnzj.core.persistence.query.CompareType;
import com.bnzj.core.persistence.query.IExpression;
import com.bnzj.core.persistence.query.QueryHelpBean;
import com.bnzj.core.rest.ResponseResult;
import com.bnzj.core.webmvc.util.WebMvcUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/exam/paper")
public class PaperReWriteController {
    @Autowired
    PaperReWriteService paperReWriteService;

    @Autowired
    PaperQuestionReWriteService paperQuestionReWriteService;

    @Autowired
    PaperSubjectReWriteService paperSubjectReWriteService;

    @Autowired
    PaperExtraReWriteService paperExtraReWriteService;


    /**
     * 试卷中心首页
     * @param request
     * @return
     */
    @GetMapping("/pageReWrite")
    public ResponseResult<Page<PaperListReWriteVO>> pageReWrite(HttpServletRequest request){

        String keyWord = request.getParameter("keyWord");
        String type = request.getParameter("type");
        // SQL语句
        QueryHelpBean queryHelpBean = PaperReWriteService.getQueryHelpBean();
        // 分页
        Pageable pageable = WebMvcUtils.initPage(request, Sort.by(Sort.Direction.DESC, "p.create_time"));
        queryHelpBean.setPageable(pageable);
        // is_delete 为 0 的条件
        IExpression build = CompareExpression.build("p.is_delete", CompareType.equal, false);
        queryHelpBean.addWhere(build);
        // 判断keyWord
        if (!StringUtils.isEmpty(keyWord)){
            IExpression build1 = CompareExpression.build("p.paper_name", CompareType.like, keyWord);
            queryHelpBean.addWhere(build1);
        }
        // 判断type
        if (!StringUtils.isEmpty(type)){
            IExpression build2 = CompareExpression.build("p.type", CompareType.equal, type);
            queryHelpBean.addWhere(build2);
        }
        // 查询
        Page<PaperListReWriteVO> all = paperReWriteService.findAll(queryHelpBean);
        return ResponseResult.success(all);

    }

    /**
     * 删除、批量删除
     * @param ids
     * @return
     */
    @PostMapping("/deleteReWrite")
    @Transactional
    public ResponseResult<Integer> deleteReWrite(@RequestBody List<Long> ids){
        Integer count = paperReWriteService.deleteReWrite(true,ids);
        return ResponseResult.success(count);
    }

    /**
     * 修改
     * @param paperReWrite
     * @return
     */
    @PostMapping("/updateReWrite")
    public ResponseResult<PaperReWrite> updateReWrite(@RequestBody PaperReWrite paperReWrite){
        // 通过id去获取数据
        PaperReWrite Paper_Target = paperReWriteService.findId(paperReWrite.getId(),false);
        if (StringUtils.isEmpty(Paper_Target)){
            throw new BusinessException(ErrorEnum.RECORD_NOT_EXIST.getMessage(), "" + ErrorEnum.RECORD_NOT_EXIST.getCode());
        }
        // 添加所需要的的数据
        SysUserVo currentUser = SystemUserUtil.getCurrentUser();
        paperReWrite.setModifyTime(new Date());
        paperReWrite.setCreator(String.valueOf(currentUser.getId()));;
        paperReWrite.setModifyName(currentUser.getCname());
        paperReWrite.setIsEnable(true); // 启动
        paperReWrite.setIsDelete(false);

        // 保存数据
        paperReWriteService.updateSave(paperReWrite,Paper_Target);
        return ResponseResult.success();
    }

    /**
     * 查看详情
     * @param id
     * @return
     */
    @GetMapping("/oneReWrite/{id}")
    public ResponseResult<PaperDetailRwWriteVO> getById(@PathVariable("id") Long id) {
        PaperDetailRwWriteVO paperDetailRwWriteVO = new PaperDetailRwWriteVO();
        // 单选数量
        Integer paperSingleCount = 0;
        // 多选数量
        Integer paperMultipleCount = 0;
        // 判断数量
        Integer paperJudgeCount = 0;
        // 通过id获取到数据
        PaperReWrite paperReWrite = paperReWriteService.findId(id, false);

        // 获取Paper-Extra的数据
        PaperExtraReWrite paperExtraReWrite = paperExtraReWriteService.getPaperExtraReWriteByPaperId(paperReWrite.getId());

        if (paperReWrite==null){
            throw new BusinessException(ErrorEnum.RECORD_NOT_EXIST.getMessage(), "" + ErrorEnum.RECORD_NOT_EXIST.getCode());
        }
        BeanUtils.copyProperties(paperReWrite,paperDetailRwWriteVO);
        // 判断试卷类型
        if (PaperTypeEnum.FIXED_SELECTION.getValue().equals(paperReWrite.getType())){
            // 固定
            // 通过paperId去获取数据
            List<Map<String, Object>> questionSubjectList = paperSubjectReWriteService.findPaperScoreByPaperIdList(paperReWrite.getId());
            if (questionSubjectList!=null){
                paperSingleCount = questionSubjectList.stream().filter(item -> SubjectTypeEnum.SINGLE_OPTION.getValue().toString().equals(item.get("type").toString())).collect(Collectors.toList()).size();
                paperMultipleCount = questionSubjectList.stream().filter(item -> SubjectTypeEnum.MULTIPLE_OPTION.getValue().toString().equals(item.get("type").toString())).collect(Collectors.toList()).size();
                paperJudgeCount = questionSubjectList.stream().filter(item -> SubjectTypeEnum.JUDGE.getValue().toString().equals(item.get("type").toString())).collect(Collectors.toList()).size();
            }
           paperDetailRwWriteVO.setQuestionSubjectList(questionSubjectList);
        }
        else if (PaperTypeEnum.RANDOM_QUESTION.getValue().equals(paperReWrite.getType())){
            // 随机
            List<Map> questionList = paperQuestionReWriteService.findQuestionByPaperId(paperReWrite.getId());
            // 创建三个集合
            List<Integer> paperSingleCountList = new ArrayList<>();
            List<Integer> paperMultipleCountList = new ArrayList<>();
            List<Integer> paperJudgeCountList = new ArrayList<>();
            if (questionList!=null){
                questionList.forEach(item->{
                    int SingleCount = item.get("singleCount") != null ? Integer.valueOf(item.get("singleCount").toString()) : 0;
                    int MultipleCount = item.get("multipleCount") != null ? Integer.valueOf(item.get("multipleCount").toString()) : 0;
                    int JudgeCount = item.get("judgeCount") != null ? Integer.valueOf(item.get("judgeCount").toString()) : 0;
                    paperSingleCountList.add(SingleCount);
                    paperMultipleCountList.add(MultipleCount);
                    paperJudgeCountList.add(JudgeCount);
                });
                if (paperSingleCountList!=null){
                    paperSingleCount = paperSingleCountList.stream().collect(Collectors.summingInt(Integer::intValue));
                }
                if (paperMultipleCountList!=null){
                    paperMultipleCount = paperMultipleCountList.stream().collect(Collectors.summingInt(Integer::intValue));
                }
                if (paperJudgeCountList!=null){
                    paperJudgeCount = paperJudgeCountList.stream().collect(Collectors.summingInt(Integer::intValue));
                }
                paperDetailRwWriteVO.setQuestionList(questionList);
            }
        }
        // 试卷单选、多选、判断题总数
        paperDetailRwWriteVO.setPaperSingleCount(paperSingleCount);
        paperDetailRwWriteVO.setPaperJudgeCount(paperJudgeCount);
        paperDetailRwWriteVO.setPaperExplainCount(0);
        paperDetailRwWriteVO.setPaperFillCount(0);
        paperDetailRwWriteVO.setPaperMultipleCount(paperMultipleCount);
        if (paperExtraReWrite!=null){
            paperDetailRwWriteVO.setTotalPaperScore(paperExtraReWrite.getPaperScore());
            paperDetailRwWriteVO.setTotalSubjectCount(paperExtraReWrite.getSubjectCount());
        }
        return ResponseResult.success(paperDetailRwWriteVO);
    }

    /**
         * 保存
         * @param paperReWrite
         * @return
         */
    @PostMapping("saveReWrite")
    @Transactional(rollbackFor = Exception.class)
    public ResponseResult<PaperReWrite> saveReWrite(@RequestBody PaperReWrite paperReWrite){
        // 添加需要的字段数据
        SysUserVo currentUser = SystemUserUtil.getCurrentUser();
        paperReWrite.setCreatorName(currentUser.getCname());
        paperReWrite.setCreator(String.valueOf(currentUser.getId()));
        paperReWrite.setCreateTime(new Date());
        paperReWrite.setIsEnable(true);
        paperReWrite.setIsDelete(false);
        // 保存数据
        paperReWriteService.saveDate(paperReWrite);
        return ResponseResult.success(paperReWrite);
    }

    /**
     * 通过id复制
     * @param id
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @PostMapping("copyReWrite/{id}")
    public ResponseResult<PaperReWrite> copyReWrite(@PathVariable("id") Long id){
        // 获取数据
        PaperReWrite paperReWrite = paperReWriteService.findId(id,false);
        if (paperReWrite ==null){
            throw new BusinessException(ErrorEnum.RECORD_NOT_EXIST.getMessage(), "" + ErrorEnum.RECORD_NOT_EXIST.getCode());
        }
        PaperReWrite paper = new PaperReWrite();
        BeanUtils.copyProperties(paperReWrite,paper);
        paper.setPaperName("(复制) "+paperReWrite.getPaperName());
        paper.setId(0L);
        // 保存数据
        paperReWriteService.saveDate(paper);
        return ResponseResult.success(paper);
    }

    /**
     * 启用
     * @param ids
     * @return
     */
    @PostMapping("/enableReWrite")
    @Transactional
    public ResponseResult<Integer> enableReWrite(@RequestBody List<Long> ids){
        Integer count = paperReWriteService.enableReWrite(true,ids);
        return ResponseResult.success(count);

    }

    /**
     * 禁用
     * @param ids
     * @return
     */
    @PostMapping("/disableReWrite")
    @Transactional
    public ResponseResult<Integer> disableReWrite(@RequestBody List<Long> ids){
        Integer count = paperReWriteService.disableReWrite(false,ids);
        return ResponseResult.success(count);

    }

}
